// 打开模态框
document.getElementById('create-folder').addEventListener('click', () => {
    let folderNameInput = document.getElementById('folderName');
    let nameError = document.getElementById('nameError');
    let createFolderModal = document.getElementById('createFolderModal');
    createFolderModal.classList.remove('hidden');
    folderNameInput.value = '';
    nameError.classList.add('hidden');
});

// 关闭模态框
document.getElementById('closeModal').addEventListener('click', () => {
    document.getElementById('createFolderModal').classList.add('hidden');
});
document.getElementById('cancelBtn').addEventListener('click', () => {
    document.getElementById('createFolderModal').classList.add('hidden');
});

document.getElementById('folderName').addEventListener('input', (e) => {
    const name = e.target.value.trim();
    const isValid = /^[^\x2f\\:*?"<>|]+$/.test(name) && name.length > 0; // 禁止常见非法字符

    if (!isValid) {
        document.getElementById('nameError').classList.remove('hidden');
    } else {
        document.getElementById('nameError').classList.add('hidden');
    }
});

// 创建文件夹逻辑
document.getElementById('createBtn').addEventListener('click', async () => {
    let folderNameInput = document.getElementById('folderName');
    let nameError = document.getElementById('nameError');
    let createFolderModal = document.getElementById('createFolderModal');

    const folderName = folderNameInput.value.trim();
    const isValid = /^[^\x2f\\:*?"<>|]+$/.test(folderName) && folderName.length > 0;

    if (!isValid) {
        nameError.classList.remove('hidden');
        return;
    }

    try {
        const token = sessionStorage.getItem("token");
        const pathList = sessionStorage.getItem("pathList") ? JSON.parse(sessionStorage.getItem("pathList")) : [];
        let path = pathList.size === 0 ? null : pathList.join("/");

        fetch('/CloudDriver_war/createfolder', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                token: token,
                path: path,
                folderName: folderName
            })
        })
            .then(response => {
                if (response.ok) {
                    createFolderModal.classList.add('hidden');
                } else {
                    throw new Error('创建文件夹失败');
                }
            })
            .catch(error => {
                console.error(error);
            });
    } catch (error) {
        console.error(error);
    }
    refreshPage();
});

// 删除文件
function removeFile(fileName) {
    const token = sessionStorage.getItem("token");
    const pathList = sessionStorage.getItem("pathList") ? JSON.parse(sessionStorage.getItem("pathList")) : [];
    let path = pathList.size === 0 ? null : pathList.join("/");
    fetch('/CloudDriver_war/removefile', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            token: token,
            path: path,
            fileName: fileName
        })
    })
        .catch(error => {
            console.error(error);
        });
    setTimeout(refreshPage, 800);
}
document.getElementById("confirmDeleteBtn").addEventListener("click", () => {
    document.getElementById("deleteModal").classList.add("hidden");
    let fileName = document.getElementById("fileToDelete").textContent;
    removeFile(fileName);
});
document.getElementById("closeDeleteModal").addEventListener("click", () => {
    document.getElementById("deleteModal").classList.add("hidden");
});
document.getElementById("cancelDeleteBtn").addEventListener("click", () => {
    document.getElementById("deleteModal").classList.add("hidden");
});
function refreshPage() {
    const token = sessionStorage.getItem("token");
    const pathList = sessionStorage.getItem("pathList") ? JSON.parse(sessionStorage.getItem("pathList")) : [];
    let path = pathList.size === 0 ? null : pathList.join("/");
    fetch("/CloudDriver_war/filelist", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: new URLSearchParams({
            token: token,
            path: path,
        })
    })
        .then(response => response.text())
        .then(html => {
            document.open();
            document.write(html);
            document.close();
        })
        .catch(error => {
            console.error("Error:", error);
        });
}
document.addEventListener("change", async(e) => {
    // 文件上传
    if (e.target.id === "file-input") {
        const files = e.target.files;
        const token = sessionStorage.getItem("token");
        const pathList = sessionStorage.getItem("pathList") ? JSON.parse(sessionStorage.getItem("pathList")) : [];
        let path = pathList.size === 0 ? null : pathList.join("/");
        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append("files", files[i]);
        }
        formData.append("token", token);
        formData.append("path", path);
        fetch("/CloudDriver_war/upload", {
            method: "POST",
            body: formData
        })
            .catch(error => {
                console.error("Error:", error);
            });
        refreshPage();
    }
})
document.addEventListener("click", async(e) => {
    // 文件上传
    if (e.target.id === "browse-files") {
        document.getElementById("file-input").click();
    }
    // 刷新页面
    if (e.target.id === "refresh") {
        refreshPage();
    }
    // 页面跳转、下载文件、删除文件
    const link = e.target.closest("a");
    if (link) {
        const pathList = sessionStorage.getItem("pathList") ? JSON.parse(sessionStorage.getItem("pathList")) : [];
        if (link.id === "backword") {
            e.preventDefault();
            pathList.pop();
            sessionStorage.setItem("pathList", JSON.stringify(pathList));
            refreshPage();
        }
        else if (link.classList.contains("forward")) {
            e.preventDefault();
            pathList.push(link.href.split('/').at(-1));
            sessionStorage.setItem("pathList", JSON.stringify(pathList));
            refreshPage();
        }
        else if (link.classList.contains("delete")) {
            e.preventDefault();
            document.getElementById("deleteModal").classList.remove("hidden");
            let fileName = link.href.split('/').at(-1);
            document.getElementById("fileToDelete").textContent = fileName;
        }
        else if (link.classList.contains("download")) {
            e.preventDefault();
            let path = pathList.join('/');
            let token = sessionStorage.getItem("token");
            let fileName = link.href.split('/').at(-1);
            fetch("/CloudDriver_war/download", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: new URLSearchParams({
                    token: token,
                    path: path,
                    fileName: fileName
                })
            })
                .then(response => {
                    if (response.status === 200) {
                        return response.blob();
                    } else {
                        throw new Error("下载失败");
                    }
                })
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement("a");
                    a.href = url;
                    a.download = decodeURIComponent(fileName);
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                })
                .catch(error => {
                    console.error("Error:", error);
                });
            refreshPage();
        }
    }
})